import router from '@/router'
import store from '@/store'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'
import { title } from './settings'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/auth-redirect', '/bind', '/register'] // 重定向白名单

router.beforeEach( async(to, from, next) => {
    NProgress.start()
    // set page title
    document.title = getPageTitle(to.meta.title)
    // 判断用户是否登录，检验token
    if (getToken()) {
        // 有token
        if (to.path === '/login') {
            next({ path: '/' })
            NProgress.done()
        }else {
            if (store.getters.roles.length === 0) {
                store.dispatch('GetInfo').then(() =>{
                    store.dispatch('GenerateRoutes').then(accessRoutes =>{
                        // 根据roles权限生成可访问的路由表
                        router.addRoutes(accessRoutes) // 动态添加可访问路由表
                        next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
                    })
                }).catch(error => {
                    store.dispatch('LogOut').then(() => {
                        Message.error(error)
                        next(`/login?redirect=${to.path}`)
                    })
                })
            }else {
                next()
            }
        }
    } else {
        // 没有token
        if (whiteList.indexOf(to.path) !== -1) {
            // 在免登录白名单，直接进入
            next()
        } else {
            next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
            NProgress.done()
        }
    }
})

router.afterEach(() => {
    // 完成进度条
    NProgress.done()
})

function getPageTitle(pageTitle) {
    if (pageTitle) {
        return `${pageTitle} - ${title}`
    }
    return `${title}`
}
